// Gooch 渲染pass
#ifndef ZXC_RP_GOOCH_PASS
#define ZXC_RP_GOOCH_PASS

#include "Common.hlsl"

#define MAX_LIGHTS 256

#define COLOR_COLD(x) float3(0.0, 0.0, 0.55) + 0.25 * (x)
#define COLOR_WARM(x) float3(0.3, 0.3, 0.0) + 0.5 * (x)
#define COLOR_HIGHLIGHT float3(1.0, 1.0, 1.0)

float4 mainLightDirection;
float4 mainLightColor;

cbuffer AdditionalLight
{
    float4 additionalLightPositions[MAX_LIGHTS];
    float4 additionalLightColors[MAX_LIGHTS];
    float4 additionalLightRanges[MAX_LIGHTS];
    float4 additionalLightSpots[MAX_LIGHTS];
}

sampler2D _MainTex;

cbuffer UnityPerMaterial
{
    float4 _Color;
}

struct Attributes
{
    float3 positionOS : POSITION;
    float3 normalOS : NORMAL;
    float2 uv : TEXCOORD;
    float3 color : COLOR;
};

struct Varyings
{
    float4 positionCS : SV_POSITION;
    float2 uv : TEXCOORD0;
    float3 positionWS : TEXCOORD1;
    float3 normalWS : TEXCOORD2;
    float3 color : TEXCOORD3;
};

struct Light
{
    float3 color;
    float3 direction;
};

Light GetMainLight(float3 positionWS)
{
    Light light;
    light.color = mainLightColor.xyz;
    light.direction = mainLightDirection.xyz;
    return light;
}

Light GetAdditionalLight(uint index, float3 positionWS)
{
    Light light;
    light.color = 0.0;
    light.direction = 0.0;
    return light;
}
            
Varyings Vert(Attributes input)
{
    Varyings output;
    output.positionCS = ObjectToHClip(input.positionOS);
    output.positionWS = ObjectToWorld(input.positionOS);
    output.normalWS = ObjectToWorldNormal(input.normalOS);
    output.uv = input.uv;
    output.color = input.color;
    return output;
}

float4 Frag(Varyings input) : SV_TARGET
{
    float3 color = tex2D(_MainTex, input.uv).rgb;
    float3 unlit = COLOR_COLD(color) * 0.5;
    float3 n = normalize(input.normalWS);
    Light mainLight = GetMainLight(input.positionWS);
    float3 r = reflect(-mainLight.direction, n);
    float3 v = normalize(cameraPos.xyz - input.normalWS);
    // float s = saturate(100.0 * dot(r, v) - 97.0);
    // float t = saturate(dot(n, mainLight.direction)) * 0.5 + 0.5;
    // float3 lit = t * mainLight.color *
    //     lerp(COLOR_WARM(color), COLOR_HIGHLIGHT, s);
    // // for(uint i = 0u; i < 0; ++i)
    // // {
    // //     Light light = GetAdditionalLight(i, input.positionWS);
    // //     lit += dot(n, light.direction) * light.color * COLOR_WARM(color);
    // // }
    // return float4(unlit + lit, 1.0);

    // fit MAD instruction (1 + LdotN) / 2 -> LdotN * 0.5 + 0.5
    float t = saturate(dot(n, mainLight.direction)) * 0.5 + 0.5;
    float3 cool = float3(0.0, 0.0, 0.55) + 0.25 * color;
    float3 warm = float3(0.3, 0.3, 0.0) + 0.5 * color;
    float3 diff = lerp(cool, warm, t);
    return float4(mainLight.color * diff, 1.0);
}

#endif